Link to this headingNumbers

Link to this headingInteger Overflow

The example below is bad because most compilers will optimize out that check.

Vulnerable Example:

size_t bytes = n * m; if (bytes < n || bytes < m) { /* BAD BAD BAD */ ... /* allocate "bytes" space */ }

Good Example:

size_t bytes = n * m; if (n > 0 && m > 0 && SIZE_MAX/n >= m) { ... /* allocate "bytes" space */ }

Link to this headingInteger Underflow

Link to this headingFloats

Link to this headingRounding Issues

Float values cannot exactly represent many decimal numbers, leading to small discrepancies that compound over time.

Rounding Floats Example:

#Calculating Fees on multiple transactions fee_rate = 0.001 # 0.1% fee total_fee = 0 for _ in range(1000): total_fee += 100 * fee_rate # Adding 1000 fees of $0.10 print(f"Expected: {100 * fee_rate * 1000}, Actual: {total_fee}") # Won't be exactly 100 #Expected: 100.0, Actual: 99.9999999999986

Numbers that are reduced by a large amount may loose precision.

Loss of significance Devision:

#Converting ETH to wei and Gwei wei_count = 10000000000005551115123126 gwei_count = wei_count / 1_000_000_000 eth_count = wei_count / 1_000_000_000_000_000_000 print(f"wei_count: {wei_count}, gwei_count: {gwei_count}, eth_count: {eth_count}") #wei_count: 10000000000005551115123126, gwei_count: 1.0000000000005552e+16, eth_count: 10000000.00000555

A large decimal value may show as truncated because it cant be stored correctly

Representation limitations:

eth = 0.100000000000000005551115123126 print(eth) #0.1 print(f"Actual value stored: {format(1.1, '.20f')}") #Actual value stored: 1.10000000000000008882

Link to this headingCalculation Issues

Summation Issues:

# Accumulating multiple trades trades = [0.1, 0.2] total_float = sum(trades) print(f"Float sum: {total_float}") #Float sum: 0.30000000000000004 # Compare with Decimal from decimal import Decimal trades_decimal = [Decimal(str(t)) for t in trades] total_decimal = sum(trades_decimal) print(f"Decimal sum: {total_decimal}") #Decimal sum: 0.3

Price Comparison:

# Price comparison in an order matching engine buy_price = 0.3 sell_price = 0.1 + 0.2 print(f"Buy price: {buy_price}") #Buy price: 0.3 print(f"Sell price: {sell_price}") #Sell price: 0.30000000000000004 print(f"Are they equal? {buy_price == sell_price}") #Are they equal? False

Order of Operations:

# Fee calculation with compounding issues trade_amount = 1234.56 fee_percentage = 0.0015 # 0.15% # Different ways to calculate the same fee fee1 = trade_amount * fee_percentage fee2 = (trade_amount * 0.15) / 100 fee3 = trade_amount / 100 * 0.15 print(f"Fee calculation 1: {fee1}") #Fee calculation 1: 1.85184 print(f"Fee calculation 2: {fee2}") #Fee calculation 2: 1.85184 print(f"Fee calculation 3: {fee3}") #Fee calculation 3: 1.8518399999999997